/**
 * Created by lijtg on 2015/10/21.
 */
$(document).ready(function () {
    var main = {
        config: {
        },
        cache: {
            timer: null,
            imgBase64: '',
            smsOtpToken: ''
        },
        startTimer: function () {
            var btn = $('#pr-btn-msgCode');
            var time = 60;
            btn.attr('disabled', 'disabled');
            btn.html('重新发送(' + time + 'S)');
            main.cache.timer = setInterval(function () {
                if(time < 0){
                    btn.attr('disabled', false);
                    btn.html('重新发送');
                    clearInterval(main.cache.timer);
                    return;
                }
                btn.html('重新发送(' + time-- + 'S)');
            }, 1000);
        },
        sendMsgCode: function (){
            var btn = $('#pr-btn-msgCode');
            if(btn.attr('disabled') == 'disabled') return;
            var phone = $('#pr-phone').val();
            if(!common.isMobile(phone)) {
                common.alertLayer({
                    errMsg: '联系人手机号有误'
                });
                return;
            }
            btn.attr('disabled', 'disabled');
            $.ajax({
                type: "POST",
                url: common.hostPath + "/api/sendMsgCode",
                data: {
                    phone: phone
                },
                dataType : 'json',
                success: function (data) {
                    if (data.errCode == "000000") {
                        main.startTimer();
                        main.cache.smsOtpToken = data.result.smsOtpToken;
                        alert("验证码： " + data.result.smsOtp);
                    }
                    else {
                        common.responseFail(data)
                    }
                },
                complete: function(xhr){
                    //main.startTimer();
                	if(!main.cache.timer){
                        btn.attr('disabled', false);
                	}
                },
                error: common.responseError
            });
        },
        submit: function (){
            var btn = $('#pr-btn-submit');
            if(btn.attr('disabled') == 'disabled') return;
            if(!main.formCheck(3)) return;

            var name = $.trim($('#pr-name').val());
            var phone = $.trim($('#pr-phone').val());
            var docType = $.trim($('#pr-docType').val());
            var docId = $.trim($('#pr-docId').val());
            var msgCode = $.trim($('#pr-msgCode').val());
            var cardId = $.trim($('#pr-cardId').val());
            var reservedPhone = $.trim($('#pr-reservedPhone').val());
            var transPwd = $.trim($('#pr-transPwd').val());
            

            btn.attr('disabled', 'disabled');
            $.ajax({
                type: "POST",
                url: common.hostPath + "/api/pOpenAcct",
                data: {
                    OPENING_FLAG: '01',
                    PRODUCT_TYPE: 'AM8010000320',
                    ACCT_NAME: name,
                    PWD_TYPE: 'WD',
                    //PASSWORD: transPwd,
                    PASSWORD: depositEncrypt.encryptByDES(transPwd),
                    VIRTUAL_AUTH_LEVEL: '03',
                    IDENTIFICATION_TYPE: docType,
                    IDENTIFICATION_NUMBER: docId,
                    NAME: name,
                    MOBILE_PHONE: phone,
                    LINKED_AGGR_TYPE: '01',
                    LINKED_BASE_ACCT_NO: cardId,
                    LINKED_BANK_CODE: main.cache.bank_code,
                    LINKED_BANK_NAME: main.cache.bank_name,
                    LINKED_ACCT_CD_TYPE: '01',
                    REG_PHONE: phone,
                    CONTACT_METHOD_TYPE: '11',
                    INDUSTRY: 'A01',
                    INDUSTRY_BELONG_TYPE: '110',
                    ZIP_CODE: '712200',
                    SOURCE_APP_ID: 'P00003A001',
            		SOURCE_PLATFORM_ID:"P00003",
            		COMPANY:"AIBANK",
            		USER_LANG:"CHINESE",
                    SMS_OTP: msgCode,
                    SMS_OTP_TOKEN: main.cache.smsOtpToken,
                    REQ_DATA:JSON.stringify(main.cache.req_data)
                },
                dataType : 'json',
                success: function (data) {
                    if (data.errCode == "000000") {
                    	var content = [
    	                    '注册成功',
    	                    '<br />',
    	                    '客户号：　' + data.result.BODY.CUSTOMER_ID,
    	                    '<br />',
    	                    '账户：　' + data.result.BODY.ACCT_DETAIL[0]["BASE_ACCT_NO"],
                    	];
                        layer.open({
                            content: content.join(''),
                            btn: '确定'
                        });
                    }
                    else {
                        common.responseFail(data)
                    }
                },
                complete: function(){
                    btn.attr('disabled', false);
                },
                error: common.responseError
            });
        },
        stepForward: function (step) {
            var line0 = $('.pr-step-container .pr-step-line-0');
            var line1 = $('.pr-step-container .pr-step-line-1');
            var width = line0.css('width');
            var number = $('.pr-step-container .pr-step-item-number');
            var text = $('.pr-step-container .pr-step-text');
            var index = step - 1;
            var percent = (parseInt(width) / 2 * index) / parseInt($('.pr-step-container').css('width')) * 100;

            line1.css('width', percent + '%');
            $(number[index]).addClass('pr-step-item-number-active');
            $(text[index]).addClass('pr-step-text-active');
        },
        stepBackWard: function (step) {
            var line0 = $('.pr-step-container .pr-step-line-0');
            var line1 = $('.pr-step-container .pr-step-line-1');
            var width = line0.css('width');
            var number = $('.pr-step-container .pr-step-item-number');
            var text = $('.pr-step-container .pr-step-text');
            var index = step - 1;
            var percent = (parseInt(width) / 2 * index) / parseInt($('.pr-step-container').css('width')) * 100;

            line1.css('width', percent + '%');
            $(number[index + 1]).removeClass('pr-step-item-number-active');
            $(text[index + 1]).removeClass('pr-step-text-active');
        },
        formCheck: function (currentStep) {
            if(currentStep == 1){
                var name = $.trim($('#pr-name').val());
                if(name == '') {
                    common.alertLayer({
                        errMsg: '姓名有误'
                    });
                    return false;
                }

                var phone = $.trim($('#pr-phone').val());
                if(!common.isMobile(phone)) {
                    common.alertLayer({
                        errMsg: '联系人手机号有误'
                    });
                    return false;
                }

                var docType = $.trim($('#pr-docType').val());
                if(docType == '') {
                    common.alertLayer({
                        errMsg: '证件类型有误'
                    });
                    return false;
                }

                var docId = $.trim($('#pr-docId').val());
                if(docId == '') {
                    common.alertLayer({
                        errMsg: '证件号码有误'
                    });
                    return false;
                }

                var msgCode = $.trim($('#pr-msgCode').val());
                if(msgCode == '') {
                    common.alertLayer({
                        errMsg: '验证码有误'
                    });
                    return false;
                }
            }

            if(currentStep == 2){
                var cardId = $.trim($('#pr-cardId').val());
                if(cardId == '' ||
                    $.trim(cardId).length < 16 ||
                    $.trim(cardId).length > 19) {
                    common.alertLayer({
                        errMsg: ' 银行卡号有误'
                    });
                    return false;
                }

                var reservedPhone = $.trim($('#pr-reservedPhone').val());
                if(!common.isMobile(reservedPhone)) {
                    common.alertLayer({
                        errMsg: ' 预留手机号有误'
                    });
                    return false;
                }
            }

            if(currentStep == 3) {
                var transPwd = $.trim($('#pr-transPwd').val());
                if (isNaN(transPwd) || transPwd.length != 6) {
                    common.alertLayer({
                        errMsg: ' 交易密码有误'
                    });
                    return false;
                }

                var transPwdConfirm = $.trim($('#pr-transPwdConfirm').val());
                if (transPwdConfirm != transPwd) {
                    common.alertLayer({
                        errMsg: ' 两次输入不一致'
                    });
                    return false;
                }
            }

            return true;
        },
        goNext: function (step) {
            //校验
            if(!main.formCheck(step - 1)) return;
            
            if(step==3){
            	var cardId = $.trim($('#pr-cardId').val());
                $.ajax({
                    type: "GET",
                    url: common.hostPath + "/api/queryBankInfo",
                    async:false,
                    data: {
                    	ACCT_NO: cardId
                    },
                    dataType : 'json',
                    success: function (data) {
                        if (data.errCode == "000000") {
                        	main.cache.bank_code=data.result.bankCode;
                        	main.cache.bank_name=data.result.bankName;
                        }
                        else {
                            common.responseFail(data)
                        }
                    },
                    complete: function(){

                    },
                    error: common.responseError
                });
            }

            main.stepForward(step);
            $('#container-' + (step - 1)).hide(1);
            $('#container-' + step).show(1);
        },
        goPre: function (step) {
            //校验
            //if(!main.formCheck()) return;

            main.stepBackWard(step);
            $('#container-' + (step + 1)).hide(1);
            $('#container-' + step).show(1);
        },
        regHammer: function () {
            var hammer = new Hammer($('#pr-btn-msgCode')[0]);
            hammer.on('tap', function (ev) {
                main.sendMsgCode();
            });
            var hammer1 = new Hammer($('#pr-btn-next')[0]);
            hammer1.on('tap', function (ev) {
                main.goNext(2);
            });
            var hammer2 = new Hammer($('#pr-btn-next2')[0]);
            hammer2.on('tap', function (ev) {
                main.goNext(3);
            });
            var hammer3 = new Hammer($('#pr-btn-pre2')[0]);
            hammer3.on('tap', function (ev) {
                main.goPre(1);
            });
            var hammer4 = new Hammer($('#pr-btn-submit')[0]);
            hammer4.on('tap', function (ev) {
                main.submit();
            });
            var hammer5 = new Hammer($('#pr-btn-pre3')[0]);
            hammer5.on('tap', function (ev) {
                main.goPre(2);
            });
            var hammer6 = new Hammer($('#pr-btn-docImage')[0]);
            hammer6.on('tap', function (ev) {
                $('#pr-docImage-input').click();
            });
        },
        init: function () {
        	main.cache.req_data = common.getUrlParams();
            main.regHammer();
            $('#pr-agree').on('change', function () {
                if($(this)[0].checked){
                    $('#pr-btn-submit').attr('disabled', false);
                }
                else{
                    $('#pr-btn-submit').attr('disabled', 'disabled');
                }
            });
            $('#pr-docType').select2().on('change', function () {
                if($(this).val() != '01'){
                    $('#pr-docImage-box').show();
                }
                else{
                    $('#pr-docImage-box').hide();
                    main.cache.imgBase64 = '';
                }
            });

            $('#pr-docImage-input').on('change', function () {
                lrz(this.files[0])
                    .then(function (rst) {
                        // 处理成功会执行
                        var img = new Image();
                        main.cache.imgBase64 = img.src = rst.base64;
                        $('#pr-docImage-view').html('').append(img)
                            .find('img').css('width', '100%').css('height', '100%');
                    })
                    .catch(function (err) {
                        // 处理失败会执行
                    })
                    .always(function () {
                        // 不管是成功失败，都会执行
                    });
            });
        }
    };

    main.init();
});